package com.example.logintest1.filter;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.logintest1.Entry.AdminMember;
import com.example.logintest1.Entry.LoginUser;
import com.example.logintest1.mapper.AdminMemberMapper;
import com.example.logintest1.until.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

//@Autowired
//    RedisCache redisCache;
@Resource
AdminMemberMapper adminMemberMapper;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        LambdaQueryWrapper<AdminMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminMember::getId, Long.valueOf(userid)); // 假设 userid 是 Long 类型
        AdminMember adminMember = adminMemberMapper.selectOne(wrapper);

        if (adminMember == null) {
            throw new RuntimeException("用户未登录");
        }

        // 创建 LoginUser 对象
        Set<String> permissions = new HashSet<>();
        permissions.add("system:dept:index"); // 确保根据实际情况填充权限
        LoginUser loginUser = new LoginUser(adminMember.getId(), adminMember.getUser(),
                adminMember.getPas(), permissions, new HashSet<>());

        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}

